<template>
	<div class="login-container">
		<el-card class="login-box">
			<h2 class="login-title">系统登录</h2>

			<el-form :model="loginForm" :rules="loginRules" ref="loginFormRef" @keyup.enter="handleLogin">
				<el-form-item prop="username">
					<el-input v-model="loginForm.username" placeholder="请输入用户名" prefix-icon="User" />
				</el-form-item>

				<el-form-item prop="password">
					<el-input v-model="loginForm.password" type="password" placeholder="请输入密码" prefix-icon="Lock"
						show-password />
				</el-form-item>

				<el-form-item prop="remember">
					<el-checkbox v-model="loginForm.remember">记住我</el-checkbox>
				</el-form-item>

				<el-form-item>
					<el-button type="primary" @click="handleLogin" :loading="loading" class="login-btn">
						登录
					</el-button>
				</el-form-item>
			</el-form>
		</el-card>
	</div>
</template>

<script setup>
	import {
		ref,
		reactive
	} from 'vue'
	import {
		ElMessage
	} from 'element-plus'
	import {
		useRouter
	} from 'vue-router'
	import axios from 'axios';
	
	const router = useRouter()

	// 登录表单数据
	const loginForm = reactive({
		username: '',
		password: '',
		remember: false
	})

	// 表单验证规则
	const loginRules = reactive({
		username: [{
				required: true,
				message: '请输入用户名',
				trigger: 'blur'
			},
			{
				min: 3,
				max: 12,
				message: '长度在 3 到 12 个字符',
				trigger: 'blur'
			}
		],
		password: [{
				required: true,
				message: '请输入密码',
				trigger: 'blur'
			},
			{
				min: 4,
				max: 18,
				message: '长度在 4 到 18 个字符',
				trigger: 'blur'
			}
		]
	})

	const loginFormRef = ref(null)
	const loading = ref(false)

	// 登录方法
	const handleLogin = () => {
		loginFormRef.value.validate(async (valid) => {
			if (!valid) return
			loading.value = true
			try {
				// 模拟登录API调用
				axios.post("http://localhost:8080/users/login", loginForm).then(function(res) {
					let token = res.data.data.token
					// 模拟登录成功
					if (token != null && token != "") {

						ElMessage.success('登录成功')
						// 存储登录状态（实际项目中应该使用更安全的方式）
						localStorage.setItem('token', token)
						// 跳转到首页
						router.push('/mainmenuvue')
					} else {
						ElMessage.error('用户名或密码错误')
					}

				}).catch(function(res) {

				})
			} catch (error) {
				ElMessage.error('登录失败: ' + error.message)
			} finally {
				loading.value = false
			}
		})
	}
</script>

<style scoped>
	.login-container {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 100vh;
		background-color: #f5f5f5;
	}

	.login-box {
		width: 400px;
		padding: 30px;
		border-radius: 8px;
		box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
	}

	.login-title {
		text-align: center;
		margin-bottom: 30px;
		color: #333;
	}

	.login-btn {
		width: 100%;
		margin-top: 10px;
	}
</style>